import {defineStore} from 'pinia'
import { LoginFormData } from '@/types/api/system/login';
import { localStorage } from '@/utils/storage';
import { userState } from '@/types/store/user';
import {login} from "@/api/login/login"
import { getMenu } from '@/api/login/user';
import Cookies from 'js-cookie'
const modules = import.meta.glob('../../views/**/**.vue')
export const Layout = () => import('@/layout/index.vue');


function ruleRoute(router:Array<Object>){
  const arr:Array<Object> = []
  router.forEach((item:any)=>{
    if(item.children?.length>0){
      ruleRoute(item.children)
    }else{
      const route = {
        path:"/",
        component:Layout,
        children:[{
          path:item.component,
          component:modules[`../../views/${item.component}/index.vue`],
          // component:import(`../../views/${item.component}/index.vue`),
          name:item.name
        }]
      }
      arr.push(route)
    }
  })
  return arr;
}



const useUserStoree = defineStore({
    id:'user',
    // 返回类型
    state: (): any =>{
        return{
            token: localStorage.get('token') || '',
            userInfo:{},
            routes:[],
            menu:[]
        }
    },
    actions:{
        async RESET_STATE(){
            this.$reset()
        },
        login(loginData:LoginFormData){
            // const {username,password} = loginData
            return new Promise((resolve,reject)=>{
                login(loginData).then((res:any)=>{
                  if(res.data.code==200){
                    const { token,userInfo } = res.data.data;
                    localStorage.set('token', token);
                    localStorage.set("userInfo",userInfo);
                    this.token = token;
                    this.userInfo = userInfo
                  }
                  resolve(res)
                })
            })
        },
        getMenuList(){
          return new Promise((resolve,reject)=>{
            getMenu().then(({data}:any)=>{
              
              // if(!data){
              //   return reject("有问题，滚去登录再来")
              // }
              // const { nickname, avatar, roles, perms } = data.data;
              // if(!roles || roles.length<=0){
              //   return reject("人家都没给你权限，偷渡人滚出中国")
              // }
              // this.nickname = nickname;
              // this.avatar = avatar;
              // this.roles = roles;
              // this.perms = perms;
              this.menu = [{path:'/dashboard',name:'首页',icon:'icon-shouye'},...data.data]
              this.routes = ruleRoute(data.data)
              
              resolve(this.routes)
            })
          })
        }
    }
})

export default useUserStoree